package com.suke.czx.modules.product.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.suke.czx.common.annotation.SysLog;
import com.suke.czx.common.base.AbstractController;
import com.suke.czx.common.utils.*;
import com.suke.czx.common.validate.ExpressUpdateGroup;
import com.suke.czx.common.validate.ProductSaveGroup;
import com.suke.czx.modules.product.entity.Product;
import com.suke.czx.modules.product.service.ProductService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 应用模块名称: 产品
 * 代码描述: 产品控制层
 * copyright: AUZAR ALL RIGHTS RESERVED
 * company: AUZAR
 *
 * @author: 颜米晨
 * @date: 2021/09/06 18:06:39
 */
@Validated
@RestController
@RequestMapping("/api/product")
@AllArgsConstructor
@Api(value = "ProductController", tags = "产品管理")
public class ProductController extends AbstractController {

    private final ProductService productService;

    /**
     * 分页查询产品列表
     * @param params 查询参数
     * @return VO
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:product:list')")
    public R list(@RequestParam Map<String, Object> params) {
        if (StrUtil.isBlankIfStr(params.get(FieldConstant.PAGE)) || StrUtil.isBlankIfStr(FieldConstant.LIMIT)) {
            return R.error("缺少分页信息");
        }
        // 查询列表数据
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(FieldConstant.DEL_FLG, CodeConstant.NOT_DEL);
        if (params.size() > 2){
            queryWrapper.like(!StrUtil.isBlankIfStr(params.get(FieldConstant.PRODUCT_NAME)), StrUtil.toUnderlineCase(FieldConstant.PRODUCT_NAME), params.get(FieldConstant.PRODUCT_NAME))
                    .like(!StrUtil.isBlankIfStr(params.get(FieldConstant.BRAND)), FieldConstant.BRAND, params.get(FieldConstant.BRAND));
        }
        IPage<Product> expressPage = productService.page(mpPageConvert.pageParamConvert(params), queryWrapper);
        return Objects.requireNonNull(R.ok().put(FieldConstant.TOTAL, expressPage.getTotal())).setData(Optional.ofNullable(expressPage.getRecords()).orElse(Lists.newArrayList()));
    }

    /**
     * 查询所有产品
     * @param productIds 产品ids
     * @return VO
     */
    @RequestMapping(value = "/select", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:product:select')")
    public R select(String productIds) {
        List<Product> dataList = productService.selectProduct(productIds);
        return Objects.requireNonNull(R.ok().put(FieldConstant.TOTAL, ListUtil.size(dataList))).setData(Optional.ofNullable(dataList).orElse(Lists.newArrayList()));
    }

    /**
     * 获取产品详情
     * @param productId 产品id
     * @return VO
     */
    @RequestMapping(value = "/info/{productId}", method = RequestMethod.GET)
    @PreAuthorize("hasRole('but:product:info')")
    public R info(@PathVariable("productId") Long productId) {
        Product product = productService.getById(productId);
        return R.ok().setData(product);
    }

    /**
     * 保存产品
     * @param product 产品
     * @param bindingResult bindingResult
     * @return VO
     */
    @SysLog("保存产品")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:product:save')")
    public R save(@Validated(ProductSaveGroup.class) Product product, BindingResult bindingResult) {
        // 入参校验结果
        if (bindingResult.hasErrors()) {
            return R.error(ParamValidateUtil.paramVilated(bindingResult));
        }
        product.setCreator(getUserId());
        product.setCreateTime(new Date());
        productService.save(product);
        return R.ok();
    }

    /**
     * 更新产品
     * @param product 产品
     * @param bindingResult bindingResult
     * @return VO
     */
    @SysLog("更新产品")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:product:update')")
    public R update(@Validated(ExpressUpdateGroup.class) Product product, BindingResult bindingResult) {
        // 入参校验结果
        if (bindingResult.hasErrors()) {
            return R.error(ParamValidateUtil.paramVilated(bindingResult));
        }
        product.setUpdater(getUserId());
        product.setUpdateTime(new Date());
        productService.updateById(product);
        return R.ok();
    }

    /**
     * 删除产品
     * @param productId 产品编码
     * @return VO
     */
    @SysLog("删除产品")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:product:delete')")
    public R delete(@NotNull(message = "产品编码不能为空") Long productId) {
        return productService.updateDelProduct(productId, getUserId());
    }

}
